/**
 * walter.pei
 */
package com.koudai.reader.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

/**
 * @author Walter
 *
 */
public class DBScriptCache {

	
	private static DBScriptCache instance = new DBScriptCache();
	
	private List<String> onCreateScripts;
	private List<String> onUpdateScripts;
	
	private DBScriptCache () {
		
	}
	
	public static DBScriptCache getInstance() {
		return instance;
	}
	
	public void init(Context context) throws DBException {
		BufferedReader bufReaderForCreate = null;
		BufferedReader bufReaderForUpdate = null;
		try {
			bufReaderForCreate = new BufferedReader(new InputStreamReader(context.getAssets().open("oncreate.png")));
			bufReaderForUpdate = new BufferedReader(new InputStreamReader(context.getAssets().open("onupdate.png")));
            
			String onCreateSQL = bufReaderForCreate.readLine();
			String onUpdateSQL = bufReaderForUpdate.readLine();
			
			while (onCreateSQL != null) {
				this.addCreateScript(onCreateSQL);
				onCreateSQL = bufReaderForCreate.readLine();
			}
			
			while (onUpdateSQL != null) {
				this.addUpdateScript(onUpdateSQL);
				onUpdateSQL = bufReaderForUpdate.readLine();
			}
		    
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new DBException("init db failed", e);
		} finally {
			try {
				bufReaderForCreate.close();
				bufReaderForUpdate.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * @return the onCreateScripts
	 */
	public List<String> getOnCreateScripts() {
		if (onCreateScripts == null) {
			onCreateScripts = new ArrayList<String>();
		}
		return onCreateScripts;
	}

	/**
	 * @return the onUpdateScripts
	 */
	public List<String> getOnUpdateScripts() {
		if (onUpdateScripts == null) {
			onUpdateScripts = new ArrayList<String>();
		}
		return onUpdateScripts;
	}
	
	public void addCreateScript(String sql) {
		getOnCreateScripts().add(sql);
	}
	
	public void addUpdateScript(String sql) {
		getOnUpdateScripts().add(sql);
	}
}
